<template>
  <!-- 已经登录的情况 -->
  <div v-if="islogin" v-loading="loading">
    <el-dropdown @command="handlerCommand">
      <div class="menu">
        <el-avatar :size="100" :src="User.logo" alt="" />
        <el-icon class="el-icon--right">
          <arrow-down />
        </el-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item>{{ User.tbUser.username }}</el-dropdown-item>
          <el-dropdown-item divided command="home">
            <el-icon><HomeFilled /></el-icon>网站首页
          </el-dropdown-item>

          <el-dropdown-item divided command="userlogo">
            <el-icon><HomeFilled /></el-icon>修改头像
          </el-dropdown-item>

          <el-dropdown-item command="userpwd">
            <el-icon><HomeFilled /></el-icon>修改密码
          </el-dropdown-item>

          <el-dropdown-item command="userinfo">
            <el-icon><HomeFilled /></el-icon>修改附加信息
          </el-dropdown-item>

          <el-dropdown-item divided command="logout">
            <el-icon><SwitchButton /></el-icon>退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <!-- {{ User }} -->
  </div>
  <!-- 没有登录的情况 -->
  <div v-if="!islogin">
    <el-buttond-group>
      <el-button @click="toPage('/user/login')" type="primary">登录</el-button>
      <el-button @click="toPage('/user/reg')" trpe="sussess">注册</el-button>
    </el-buttond-group>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { api } from '../../js/ajax'
import { tools } from '../../js/tools'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'

const router = useRouter()

const loading = ref(false)

const handlerCommand = command => {
  if (command == 'logout') {
    api.delete('/auth', {}, () => {
      queryUser()
    })
  } else if (command == 'home') {
    router.push('/')
  } else if (command == 'userlogo') {
    modifyUserLogo()
  }
}

const modifyUserLogo = () => {
  tools.openImage(File => {
    loading.value = true
    api.uploadUserLogo(File, data => {
      loading.value = false
      if (data.success) {
        queryUser()
        return
      }
      ElMessageBox.alert(data.message, '修改头像失败')
    })
  })
}

const toPage = page => {
  router.push(page)
}

const islogin = ref(false)
const User = ref({
  tbUser: {},
  tbUserInfo: {},
  tbRole: {},
  exInfo: {},
  logo: '',
})

const queryUser = () => {
  api.get('/auth', {}, data => {
    islogin.value = data.success
    if (data.success) {
      User.value = data.data
      User.value.logo = api.userlogo(data.data.tbUser.uid)
    } else {
      User.value = {
        tbUser: {},
        tbUserInfo: {},
        tbRole: {},
        exInfo: {},
        logo: '',
      }
    }
  })
}
queryUser()
</script>

<style scoped>
.menu {
  display: flex;
  align-items: center;
}
.menu img {
  width: 8rem;
  height: auto;
  display: block;
  border-radius: 50%;
}
.el-tooltip__trigger {
  outline: none;
}
</style>
